# -*- coding: utf-8 -*-

import arcpy
import os
from datetime import datetime
from pypinyin import lazy_pinyin

class Toolbox(object):
    def __init__(self):
        """Define the toolbox (the name of the toolbox is the name of the
        .pyt file)."""
        self.label = "Toolbox"
        self.alias = "toolbox"

        # List of tool classes associated with this toolbox
        self.tools = [SplitArea]


class SplitArea(object):
    def __init__(self):
        """Define the tool (tool name is the name of the class)."""
        self.label = "拆分房屋面"
        self.description = "拆分房屋面为不修改、要修改、构筑物"
        self.canRunInBackground = False

    def getParameterInfo(self):
        """Define parameter definitions"""

        param0 = arcpy.Parameter(
            displayName="房屋面路径",
            name="path_to_check",
            datatype="DEFolder",
            parameterType="Required",
            direction="Input")

        param0.value = r"E:\MyDocument\ArcGis\DT\基地面修改"

        param1 = arcpy.Parameter(
            displayName="乡镇名",
            name="townName",
            datatype="GPString",
            parameterType="Required",
            direction="Input")

        param1.filter.type = "ValueList"
        param1.filter.list = ["梅川镇", "花桥镇", "大法寺镇", "龙坪镇", "四望镇"]

        param2 = arcpy.Parameter(
            displayName="图层",
            name="target_layer_name",
            datatype="GPFeatureLayer",
            parameterType="Required",
            direction="Input"
        )

        params = [param0, param1, param2]
        return params

    def isLicensed(self):
        """Set whether tool is licensed to execute."""
        return True

    def updateParameters(self, parameters):
        """Modify the values and properties of parameters before internal
        validation is performed.  This method is called whenever a parameter
        has been changed."""
        return

    def updateMessages(self, parameters):
        """Modify the messages created by internal validation for each tool
        parameter.  This method is called after internal validation."""
        return

    def check_and_create_folder(self, folder_path, folder_name, messages):
        full_path = os.path.join(folder_path, folder_name)

        if not os.path.exists(full_path):
            os.makedirs(full_path)
            messages.addMessage(f"文件夹 '{folder_name}' 已创建。")
        else:
            messages.addMessage(f"文件夹 '{folder_name}' 已存在。")

        return full_path
    
    def create_town(self, base_path, townName, messages):
        # 检查并创建镇文件夹
        town_folder = self.check_and_create_folder(base_path, townName, messages)

        return town_folder

    def execute(self, parameters, messages):
        """The source code of the tool."""
        isagain = False
        version = "02"
        path_to_check = parameters[0].valueAsText
        folder_to_find = datetime.now().strftime("%m%d")

        base_path = self.check_and_create_folder(path_to_check, folder_to_find, messages)
        townName = parameters[1].valueAsText
        town_folder = self.create_town(base_path, townName, messages)

        # 获取当前工程
        aprx = arcpy.mp.ArcGISProject("CURRENT")
        # 获取活动的地图或场景
        active_map_or_scene = aprx.activeMap

        target_layer_name = parameters[2].valueAsText
        target_layer = None
        for lyr in active_map_or_scene.listLayers():
            if lyr.name == target_layer_name:
                target_layer = lyr
                break

        if target_layer is None:
            messages.addErrorMessage("图层未找到。")
            exit

        # 连接参数
        sheet_name = "Sheet1$"
        in_field = "uuid"
        join_field = "MOID"

        # 添加连接
        veg_joined_table = arcpy.management.AddJoin(
            target_layer_name,
            in_field,
            sheet_name,
            join_field)

        # 拆分文件 要修改、不修改、构筑物
        modify_name = townName + "_要修改" + (version if isagain else '')
        modify_path = os.path.join(town_folder, modify_name)
        nomodify_name = townName + "_不修改" + (version if isagain else '')
        nomodify_path = os.path.join(town_folder, nomodify_name)
        delete_name = townName + "_构筑物" + (version if isagain else '')
        delete_path = os.path.join(town_folder, delete_name)
        wh_name = townName + "_中心镇区" + (version if isagain else '')
        wh_path = os.path.join(town_folder, wh_name)

        output_layer_arr = []

        expriession = "Sheet1$.WTBH = '删除'"
        out_layer_delete, countStr = arcpy.management.SelectLayerByAttribute(
            target_layer,
            "NEW_SELECTION",
            expriession)
        messages.addMessage(f"构筑物数量：'{countStr}'")

        count = int(countStr)
        if count > 0:
            arcpy.conversion.ExportFeatures(out_layer_delete, delete_path)
            output_layer_arr.append(delete_path)

        expression = "Sheet1$.WTBH = '拆分' Or Sheet1$.WTBH = '合并' Or Sheet1$.WTBH = '其他'"
        out_layer_modify, countStr = arcpy.management.SelectLayerByAttribute(
            target_layer, 
            "NEW_SELECTION", 
            expression)
        messages.addMessage(f"要修改数量：'{countStr}'")       

        modify_count = int(countStr)
        if modify_count > 0:
            arcpy.conversion.ExportFeatures(out_layer_modify, modify_path)
            output_layer_arr.append(modify_path)

        expression = "Sheet1$.MOID IS NULL"
        out_layer_nomodify, countStr = arcpy.management.SelectLayerByAttribute(
            target_layer,
            "NEW_SELECTION",
            expression)
        messages.addMessage(f"未修改数量：'{countStr}'")

        count = int(countStr)
        if count > 0:
            if modify_count == 0:
                arcpy.conversion.ExportFeatures(out_layer_nomodify, wh_path)
                output_layer_arr.append(wh_path)
            else:
                arcpy.conversion.ExportFeatures(out_layer_nomodify, nomodify_path)
                output_layer_arr.append(nomodify_path)
            

        # 移除连接
        arcpy.management.RemoveJoin(target_layer_name)

        # 移除图层
        if target_layer:
            messages.addMessage(f"正在移除图层：{target_layer.name}")
            active_map_or_scene.removeLayer(target_layer)
            # 保存更改到工程文件
            aprx.save()
            messages.addMessage("图层移除完成，并已保存更改")
        else:
            messages.addMessage(f"未找到名为 '{target_layer.name}' 的图层")

        # 添加新增图层
        for layer_file in output_layer_arr:
            try:
                # 添加图层到地图或场景
                layer_path = layer_file + ".shp"
                active_map_or_scene.addDataFromPath(layer_path)
                messages.addMessage(f"已添加图层: {layer_path}")
            except Exception as ex:
                messages.addMessage(f"未能添加图层 '{layer_path}' 到地图或场景: {ex}")

        return

    def postExecute(self, parameters):
        """This method takes place after outputs are processed and
        added to the display."""
        return
